#include <iostream>
#include <thread>
#include <deque>
#include <ctime>
#include <mutex>
using namespace std;
#define THREAD 5

int ticket = 10;
mutex m;

void run()  //普通的函数，用来执行线程
{
	while(ticket > 0)
	{
		m.lock();
		--ticket;
		printf("thread %d buy a ticket, remain a piece of %d\n", std::this_thread::get_id(), ticket);
		if(ticket <= 0)
			cout << "thread " << std::this_thread::get_id() << " come later " << endl;
		m.unlock();
		this_thread::sleep_for(std::chrono::milliseconds(500));
	}
}
int main()
{
	thread th[THREAD];  //实例化一个线程对象th1，使用函数t1构造，然后该线程就开始执行了
	cout << "main thread number : " << std::this_thread::get_id() << endl;
	clock_t start,end;

	start = clock();

	for (int i = 0; i < THREAD; ++i)
	{
		th[i] = thread(run);
	}
	for (int i = 0; i < THREAD; ++i)
	{
		th[i].join();
	}

	end = clock();

	cout << "the run time is :"<<(double)(end - start) / CLOCKS_PER_SEC<<"s\n\n";
 
	return 0;
}